package endpoint

import (
	"center/db"
	"common/pb"
	"context"
	"errors"
	"go.uber.org/zap"
)

func (s *MetainfoServer) UploadNodeSelection(ctx context.Context, req *pb.UploadNodeSelectionRequest) (res *pb.UploadNodeSelectionResponse, err error) {
	defer func() {
		err = Error.Wrap(err)
		s.log.Info("UploadNodeSelection",
			zap.Int32("quantity", req.Quantity), zap.Error(err))
	}()
	_, err = s.validateAuth(ctx, req.Header)
	if err != nil {
		return
	}
	nodes, err := s.db.GetUploadNodesByWeight(ctx, &db.NodeSelection{
		Quantity:      int(req.Quantity),
		IncludeNodeId: req.IncludeNodeId,
		ExcludeNodeId: req.ExcludeNodeId,
		MinVersion:    s.config.MinNodeVersion,
	})
	if len(nodes) == 0 {
		err = errors.New("no nodes found")
		return
	}
	res = &pb.UploadNodeSelectionResponse{
		Header:   req.Header,
		NodeInfo: nil,
	}
	for _, n := range nodes {
		res.NodeInfo = append(res.NodeInfo, &pb.NodeInfo{
			NodeId: n.ID.Bytes(),
			StorageNodeAddress: &pb.NodeAddress{
				Ip:       n.Ip,
				Ipv6:     n.Ipv6,
				DeviceId: n.DevId,
				Port:     int32(n.Port),
				Nat:      int32(n.Nat),
			},
			PeerFwd: int32(n.Fwd),
		})
	}
	return
}
